<?php
namespace app\api\server\payment;
use app\command\Order;
use app\logic\model\MintTransferLogModel;

use app\logic\model\PlatformMoneyLogModel;

use app\api\model\OpusModel;
use app\api\model\OpusNumberModel;
use app\api\model\order\OrderOpusModel;
use app\api\model\UserModel;
use think\cache\driver\Redis;
use think\Request;
use think\facade\Db;
use think\facade\Log;
use app\Common as appCommon;
use app\api\model\order\ShadowOrder as ShadowOrderModel;
/**
 * @Propuse 此接口不进行验证是否登陆 
 * @desc 支付回调方法
 */
class Notify{
	protected $request;
	protected static $s_model_shadow;
	protected $addSettingParam=array();
	use Nft;
	public function __construct()
    {
    	self::$s_model_shadow=new ShadowOrderModel();
    }
    
	/**
	 * @Purpose 影映品订单支付成功
	 */
	public function payment($_param){
		//开启事务
    	Db::startTrans();
    	Log::record("=============================支付回调开始============================");
    	//1处理corepay状态防止一个订单多次执行回调方法
    	$_up_flag=$this->updateCorePay($_param);
    	if($_up_flag==false){
    		Db::rollback();
    		return false;
    	}
    	//2.处理订单状态及记录订单数据
    	$_updata_order_flag=$this->updateOrder($_param);
    	if($_updata_order_flag==false){
    		Db::rollback();
    		return false;
    	}
    	Db::commit();
    	Log::record("=============================支付回调正常结束============================");
    	return true;
	}
	
    public $pay_type=[
    	'0'=>'2',//微信小程序
    	'1'=>'3',//微信公众号
    ];
	public function updateOrder($param){
    	$id=$param['order_id'];
    	$_order=self::$s_model_shadow->findOrder(["id"=>$id],"*");
    	if($_order['status']==1){
    		Log::record(__function__.":".__line__."\r\n"."支付回调已完成不需要继续回调");
    		return false;
    	}
    	//1.更新状态并记录当前支付参数
    	$_order_up=[
    		'transaction_id'=>$param['transaction_id'],
    		'pay_time'=>time(),
    		'pay_type'=>$this->pay_type[$param['type']],
    		'status'=>1,
    	];
    	$_order_update_flag=self::$s_model_shadow->updateOrder($_order_up,$_where=['id'=>$id]);
    	if(!$_order_update_flag){
    		Log::record(__function__.":".__line__."\r\n"."更新订单状态失败");
    		Log::record(__function__.":".__line__."\r\n"."up:".json_encode($_order_up)."|where:".json_encode($_where));
    		return false;
    	}
    	$_order_operation=[
    		'shadow_id'=>$id,
    		'type'=>1,
    		'create_time'=>time()
    	];
    	if(!($_order_id=self::$s_model_shadow->insertOrderOperation($_order_operation))){
			Log::record(__function__.":".__line__."\r\n"."添加支付成功记录日志失败");
    		Log::record(__function__.":".__line__."\r\n"."insert:".json_encode($_order_operation));
			return false;
		}
    	return true;
    }
    
    public function updateCorePay($param){
    	$id=$param['id'];
    	if($param['status']==1){
    		$this->error="支付回调失败。当前支付已完成不需要继续回调";
    		Log::record(__function__.":".__line__."\r\n"."支付回调失败。当前支付已完成不需要继续回调");
    		return false;
    	}
    	Log::record(__function__.":".__line__."\r\n"."支付回调更新corePay状态");
    	$_updata_flag=self::$s_model_shadow->upOrderCorePay($_up=['status'=>1,'up_time'=>time()],$_where=['id'=>$id]);
    	Log::record(__function__.":".__line__."\r\n"."支付回调更新corePay状态:".$_updata_flag);
    	Log::record(__function__.":".__line__."\r\n"."up:".json_encode($_up)."|where:".json_encode($_where));
    	if($_updata_flag==false){
    		$this->error="支付回调更新corePay状态:";
    		return false;
    	}
    	return true;
    }

    public function paymentOrderOpus($order){
        $orderOpus=(new OrderOpusModel())->getList(['order_pay_id'=>$order['id']],"*",9999,false);

        $userModel=new UserModel();
        $opusNumberModel=new OpusNumberModel();
        $mintTransferLogModel= new MintTransferLogModel();
        $opus=(new OpusModel())->getFindByid($orderOpus[0]['opus_id']);
        $seller=(new UserModel())->getFindByid($order['seller_id']);
        $buyer=(new UserModel())->getFindByid($order['buyer_id']);
        $mintTransferLog=[
            'opus_id'=>$opus['id'],
            'is_transfer'=>1,
            'transfer_to_user_id'=>$order['buyer_id'],
            'transfer_from_user_id'=>$order['seller_id'],
            'type'=>1,
            'oid'=>$order['id'],
        ];
        $transfer_opus_number_id=[];
        $cantTransfer=1;/**是否可以转移**/
        /**如果当前作品没有铸造NFT,铸造nft**/
        /*if($opus['is_nft']==-1){
            //铸造NFT地址,不要让铸造NFT影响 内部系统逻辑
            $mintTransferLog['is_mint']=1;
            $mintTransferLog['mint_user_id']=$opus['writer_id'];
            $mintTransferLog['transfer_from_user_id']=$opus['writer_id'];
            $nftCount=$opusNumberModel->getCount(['opus_id'=>$opus['id']]);
            $nftPics=[['pic'=>$opus['img']]];
            //开始铸造
            $nftRes=$this->mint(
                $seller['nickname'].date('Y-m-d H:i:s'),
                $seller['nft'],$nftPics,
                $nftCount);
            $mintTransferLog['mint_message']=$nftRes['message'];
            //铸造成功后，将每个编号都放入nft地址

            if($nftRes['code']==200){
                $mintTransferLog['status']=1;
                $allOpusNumber=$opusNumberModel->getList(['opus_id'=>$opus['id']],'*',9999,true);
                $single_work_list=$nftRes['data']['work_info']['single_work_list'];
                foreach ($allOpusNumber['data'] as $key=>$val){
                    $opusNumberModel->where('id',$val['id'])->save(['nft'=>$single_work_list[$key]['id_index'],'nft_status'=>1]);
                }
                $opus->is_nft=1;
                $opus->save();
            }else{
                $cantTransfer=0;
            }
        }*/
        Db::startTrans();
        Log::record("=============================NFT支付回调开始============================");
        try {
            //修改主订单状态
            $orderOpusUpdate=array(
                'status'=>1,
                'pay_time'=>time(),

            );
            /**如果购买者不是藏家，则设置为藏家-开始**/
            /*$buyer=(new UserModel())->getFindByid($order['buyer_id']);
            if($buyer['is_collectors']==-1){
                (new UserModel())->where('id',$buyer['id'])->save(['is_collectors'=>1]);
            }*/
            /**如果购买者不是藏家，则设置为藏家-结束**/
            /**不管是购买原创作品还是作品编号都需要转移**/

            $redis=new redis();
            $transfer_ids=[];
            if(is_array($orderOpus)) {
                foreach ($orderOpus as $key=>$val){
                    $transfer_opus_number_id[]=$val['opus_number_id'];
                    $userModel->commission($val);//给予佣金+日志
                    $opusNumber=$opusNumberModel->where('id',$val['opus_number_id'])->find();
                    $orderOpusUpdate['opus_number_buy_num']=$opusNumber['buy_num']+1;
                    $a=(new OrderOpusModel())->updateOrder($val['id'],$orderOpusUpdate);
                    //修改作品编码
                    $opusNumberModel->modifyOwner($val['buyer_id'],$val['opus_number_id']);
                    //记录日志
                    (new OpusNumberModifyOwnerLog())->createLog($opusNumber['owner_uid'],$val['buyer_id'],$opusNumber['id'],1,'购买');
                    //增加卖家余额和日志
                    $title='收入-'.$opus['title'];
                    $remark='订单编号'.$order['ordersn'];
                    (new UserModel())->setBalance($val['seller_id'],$val['seller_price'],4,1,$title,$remark,$val['id']);
                    //增加作家余额和日志(作家版权费)
                    if($order['write_copyright_price']>0){
                        $title='收入(版权)-'.$opus['title'];
                        $remark='订单编号'.$order['ordersn'];
                        (new UserModel())->setBalance($opus['writer_id'],$val['write_copyright_price'],3,1,$title,$remark,$val['id']);
                    }
                    $transfer_ids[]=$opusNumber['nft'];
                    //增加平台服务费比例
                    if($val['platform_price']>0){
                        $platformMoneyLog=array(
                            'capital_type'=>1,
                            'order_id'=>$val['id'],
                            'order_type'=>1,
                            'price'=>$val['platform_price'],
                            'type'=>1,
                        );
                        (new PlatformMoneyLogModel())->save($platformMoneyLog);
                    }
                }
            }
            /**如果作品都被购买了，修改状态为 -2（已售罄）**/
            $count=$opusNumberModel->getCount(['opus_id'=>$opus['id'],'writer_have'=>1]);
            if($count==0){
                $opus->status=-2;
                $opus->save();
            }

            $order->status=1;
            $order->pay_time=$orderOpusUpdate['pay_time'];
            $order->save();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
        //(new Order())->setRedisLockOrderOpusOpusNumber();
        if($cantTransfer){

            $mintTransferLog['transfer_opus_number_id']=implode(',',$transfer_opus_number_id);

            /**转移nft开始**/
            $transferRes=$this->transfer($seller['nft'],$buyer['nft'],$transfer_ids);
            $mintTransferLog['transfer_message']=$transferRes['message'];
            $mintTransferLogModel->save($mintTransferLog);
        }
        Log::record("=============================NFT支付回调正常结束============================");

        return true;
    }
}
?>